from flask import g, current_app
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from models import db
from models.user import User, UserProfile
from utils import parser
from utils.decorators import login_required

from utils.storage import upload_image
from cache import user as cache_user
from cache import statistic as cache_statistic

class PhotoResource(Resource):
    method_decorators = [login_required]

    def patch(self):
        """
        更新
        :return:
        """

        # 创建对象

        file_parser = RequestParser()

        file_parser.add_argument('photo',type=parser.image_file,required=True,location='files')

        files = file_parser.parse_args()

        image_file = files['photo']

        #上传图片到七牛云
        image_data = image_file.read()
        file_name = upload_image(image_data)

        # 保存到数据库
        User.query.filter(User.id == g.user_id).update({'profile_photo': file_name})
        db.session.commit()

        photo_url = current_app.config['QINIU_DOMAIN'] + file_name
        return {'photo_url':photo_url},201

# /users/<int(min=1):user_id>/

class UserResource(Resource):
    """用户资料接口"""

    def get(self,user_id):

        # 校验参数
        # 业务处理
        # 查询用户信息
        # 返回
        cache_tool = cache_user.UserProfileCache(user_id)
        if not cache_tool.determine_user_exists():
            # 用户不存在
            return {"message":"User does not exist"},400

        user_dict = cache_tool.get()

        del user_dict["mobile"]
        user_dict["user_id"] = user_id
        user_dict["photo"] = current_app.config['QINIU_DOMAIN'] + user_dict["photo"]

        user_dict['article_count'] = cache_statistic.UserArticlesCountStorage.get(user_id)
        user_dict['follows_count'] = cache_statistic.UserFollowingCountStorage.get(user_id)
        user_dict['fans_count'] = cache_statistic.UserFansCountStorage.get(user_id)
        user_dict['liking_count'] = cache_statistic.ArticleCollectingCountStorage.get(user_id)
        # todo
        return user_dict





